var rAF = window.requestAnimationFrame  ||
    window.webkitRequestAnimationFrame  ||
    window.mozRequestAnimationFrame     ||
    window.oRequestAnimationFrame       ||
    window.msRequestAnimationFrame      ||
    function (callback) { window.setTimeout(callback, 1000 / 60); };
Array.prototype.find = function(ele){
  var len = this.length;
  for(var i = len-1; i >= 0; i--){
    if(this[i] == ele){
      return i;
    }
  }
  return -1;
}
function Question(q){
    var qdom = document.createElement('div');
    var title = document.createElement('div');
    var pt = document.createElement('p');
    pt.innerHTML = q.title;
    pt.style.margin = '30px 0px';
    pt.style.padding = '0px 20px';
    pt.style.fontSize = '20px';
    title.appendChild(pt);
    qdom.appendChild(title);
    var choiceArea = document.createElement('div');
    var clen = q.choices.length;
    for(var i = 0; i < clen; i++){
        var c = document.createElement('div');
        c.innerHTML = q.choices[i].text;
        c.classList.add('choice');
        c.id = i+'choice';
        c.style.margin = 'auto';
        c.style.marginBottom = '20px';
        c.style.width = '80%';
        c.style.backgroundColor = '#fff';
        c.style.padding = '10px 15px';
        c.style.borderRadius = '5px';
        choiceArea.appendChild(c);
    }
    qdom.appendChild(choiceArea);
    var elems = choiceArea.querySelectorAll('.choice');
    for(var i = 0;  i < elems.length; i++){
        elems[i].addEventListener('click',function(){
            var curCard = cc.getCurCard();
            curCard.enablePullup();
            var id = parseInt(this.id);
            if(curQuestionSelected >= 0){
                elems[curQuestionSelected].style.backgroundColor = '#fff';
            }
            curQuestionSelected = id;
            this.style.backgroundColor = 'rgb(253, 191, 30)';
        })
    }
    return qdom;
}
function createQuestion(title,choices){
    $.ajax({
        url:'/createQuestion',
        type:'post',
        data:{
            author:memberId,
            title:title,
            choices:choices
        },
        success:function(reply){
            if(reply.status == 'success'){
                alert('发布题目成功,点击确认后刷新页面查看');
                window.location.reload();
            }
            else{
                alert('发布题目失败,原因可能是:'+reply.message);
            }
        },
        error:function(err){
            output(err);
        }
    });
}
function submitQuestion(questionId,choiceIndex){
    $.ajax({
        url:'/submitQuestion',
        type:'post',
        data:{
            memberId:memberId,
            questionId:questionId,
            choiceIndex:choiceIndex
        },
        success:function(reply){
            if(reply.status == 'success'){
                answeredNumber++;
                if(!isAdmin&&answeredNumber>=Math.min(10,questionArray.length)){
                    alert('恭喜你已经成为管理员,点击确认后刷新页面查看');
                    window.location.reload();
                }
            }
            else{
                alert('提交回答失败,原因可能是:'+reply.message);
            }
        },
        error:function(err){
            output(err);
        }
    });
}
function supportQuestion(questionId){
    $.ajax({
        url:'/supportQuestion',
        type:'post',
        data:{
            memberId:memberId,
            questionId:questionId
        },
        success:function(reply){
            output(reply);
        },
        error:function(err){
            output(err);
        }
    });
}
function opposeQuestion(questionId){
    $.ajax({
        url:'/opposeQuestion',
        type:'post',
        data:{
            memberId:memberId,
            questionId:questionId
        },
        success:function(reply){
            output(reply);
        },
        error:function(err){
            output(err);
        }
    });
}
function getNextQuestion(){
    var before = nextQuestionIndex;
    var len = questionArray.length;
    for(var i = nextQuestionIndex+1; i < len; i++){
        var q = questionArray[i];
        var clen = q.choices.length;
        var flag = true;
        for(var j = 0; j < clen; j++){
            if(q.choices[j].members.find(memberId)>=0){
                flag = false;
                break;
            }
        }
        if(flag){
            nextQuestionIndex = i;
            break;
        }
    }
    if(nextQuestionIndex == before){
        nextQuestionIndex = questionArray.length;
    }
}
function randomChar(l){
    var x="123456789poiuytrewqasdfghjklmnbvcxzQWERTYUIPLKJHGFDSAZXCVBNM";
    var tmp="";
    for(var i=0;i< l;i++) {
        tmp += x.charAt(Math.ceil(Math.random()*100000000)%x.length);
    }
    return tmp;
}
function loadCard(index){
    if(index<1){return;}
    if(index == 1&&!isAdmin){
        var second = document.createElement('div');
        var p = document.createElement('p');
        var introduce = "我们是北京大学通选课程社会心理学的小组成员，希望通过问卷的"
        +"形式调研在校同学对北京大学这个集体的归属感，参与调研的同学的所有信息将会被完全保密，"
        +"调研数据只会用于课程报告。希望感兴趣的同学参与填写问卷，本问卷不要求完成所有题目，"
        +"参与者可以根据自己的兴趣和时间分次填写，当参与者完成10道题后即可以自己出题加入到本次调研,"
        +"将本页面往上拉就可以开始参与调研啦！";
        p.innerHTML = introduce;
        p.style.fontSize = '16px';
        p.style.padding = '10px 20px';
        p.style.lineHeight = '25px';
        second.appendChild(p);
        var curCard = cc.newCard(second,'少年，回不去了。',null,'放手往前走吧！');
        curCard.enablePullup();
        return;
    }
    if(curQuestionSelected>=0&nextQuestionIndex>=0&&nextQuestionIndex<questionArray.length){
        submitQuestion(questionArray[nextQuestionIndex]._id,curQuestionSelected);
    }
    getNextQuestion();
    if(nextQuestionIndex>=0&&nextQuestionIndex<questionArray.length){
        curQuestionSelected = -1;
        var newQuestion = new Question(questionArray[nextQuestionIndex]);
        if(isAdmin){
            var curCard = cc.newCard(newQuestion,'返回管理员页面','请先作答','放手往前走吧！');
            curCard.enablePulldown();
        }
        else{
            var curCard = cc.newCard(newQuestion,'少年，回不去了。','请先作答','放手往前走吧！');
        } 
    }
    else{
        alert('没有更多的题目了,点击确认后刷新页面');
        window.location.reload();
    }
}
function output(data){
    for(var key in data){
        console.log(key+'='+data[key]);
    }
}
function showPoetry(desktop){
    var poetry = ['一个人走在路上',
    '来往的人好像都忙着各自的事情',
    '那几个少女在一块说笑',
    '那几个少年在一起谈天',
    '只有我自己',
    '望着影子走过',
    '我以为我存在于这里',
    '我以为我归属于这里',
    '但好像',
    '没有什么印记能证明'];
    var len = poetry.length;
    var poetryContainer = document.createElement('div');
    poetryContainer.style.marginTop = '20px';
    poetryContainer.style.opacity = '0';
    poetryContainer.style.overflow = 'hidden';
    poetryContainer.style.textAlign = 'center';
    for(var i = 0; i < len; i++){
        var tmp = document.createElement('p');
        tmp.innerHTML = poetry[i];
        poetryContainer.appendChild(tmp);
    }
    function showArrowDown(){
        var arrow = document.createElement('div');
        arrow.style.margin = 'auto';
        arrow.style.background = 'url(img/pull.png) 0 0 no-repeat';
        arrow.style.width = '40px';
        arrow.style.height ='40px';
        arrow.style.marginTop = '20px';
        arrow.style.backgroundSize = '40px 80px';
        desktop.appendChild(arrow);
    }
    $(document).ready(function(){
        var maxH = poetryContainer.offsetHeight;
        var curH = 0;
        poetryContainer.style.opacity = '1';
        rAF(animation);
        function animation(){
            curH += 0.3;
            poetryContainer.style.height = curH+'px';
            if(curH<maxH){
                rAF(animation);
            }
            else{
                showArrowDown();
            }
        }
    });
    desktop.appendChild(poetryContainer);
}
function addAnswer(){
    if(curAnswerNumber>answerInputArray.length){
        alert('如果你不是黑客,那就是系统出错咯！');
        return;
    }
    if(curAnswerNumber==answerInputArray.length){
        curAnswerNumber++;
        var answerArea = document.querySelector('#answerArea');
        var answerItem = document.createElement('div');
        answerItem.id = 'answerItem'+curAnswerNumber;
        answerArea.appendChild(answerItem);
        p = document.createElement('p');
        p.innerHTML = '请输入选项'+curAnswerNumber;
        answerItem.appendChild(p);
        var answerInput = document.createElement('textarea');
        answerInput.rows = 2;
        answerItem.appendChild(answerInput);
        answerInputArray.push(answerInput);
    }
    else{
        curAnswerNumber++;
        document.getElementById('answerItem'+curAnswerNumber).style.display = 'block';
    }
    var curCard = cc.getCurCard();
    curCard.scroll.refresh();
}
function deleteAnswer(){
    if(curAnswerNumber<3){return;}
    var answerItem = document.getElementById('answerItem'+curAnswerNumber);
    answerItem.style.display = 'none';
    curAnswerNumber--;
    var curCard = cc.getCurCard();
    curCard.scroll.refresh();
}
function doSubmit(){
    var title = titleInput.value;
    if(title == ''){
        titleInput.focus();
        return;
    }
    var array = [];
    for(var i = 1; i <= curAnswerNumber; i++){
        var c = answerInputArray[i-1].value;
        if(c == ''){
            answerInputArray[i-1].focus();
            return;
        }
        else{
            array.push(c);
        }
    }
    if(array.length<2){
        alert('如果你不是黑客,那就是系统出错咯！');
    }
    else{
        createQuestion(title,array);
    }
}
function initCreate(){
    var ca = document.querySelector('#createArea');
    ca.innerHTML = '';
    var p = document.createElement('p');
    p.innerHTML = '请输入题目';
    ca.appendChild(p);

    titleInput = document.createElement('textarea');
    titleInput.rows = 3;
    ca.appendChild(titleInput);
    var answerArea = document.createElement('div');
    answerArea.id = 'answerArea';
    ca.appendChild(answerArea);

    var answerItem = document.createElement('div');
    answerItem.id = 'answerItem1';
    answerArea.appendChild(answerItem);
    p = document.createElement('p');
    p.innerHTML = '请输入选项1';
    answerItem.appendChild(p);
    answerInputArray = [];
    var answerInput = document.createElement('textarea');
    answerInput.rows = 2;
    answerItem.appendChild(answerInput);
    answerInputArray.push(answerInput);

    answerItem = document.createElement('div');
    answerItem.id = 'answerItem2';
    answerArea.appendChild(answerItem);
    p = document.createElement('p');
    p.innerHTML = '请输入选项2';
    answerItem.appendChild(p);
    answerInput = document.createElement('textarea');
    answerInput.rows = 2;
    answerItem.appendChild(answerInput);
    answerInputArray.push(answerInput);

    var commandArea = document.createElement('div');
    ca.appendChild(commandArea);
    commandArea.style.marginTop = '20px';
    commandArea.style.height = '40px';

    var addAnswerButton = document.createElement('div');
    addAnswerButton.innerHTML = '添加选项';
    addAnswerButton.classList.add('activeButton');
    addAnswerButton.style.padding = '10px 0px';
    addAnswerButton.style.width = '45%';
    addAnswerButton.style.float = 'left';
    commandArea.appendChild(addAnswerButton);

    var deleteAnswerButton = document.createElement('div');
    deleteAnswerButton.innerHTML = '删除选项';
    deleteAnswerButton.classList.add('activeButton');
    deleteAnswerButton.style.padding = '10px 0px';
    deleteAnswerButton.style.width = '45%';
    deleteAnswerButton.style.float = 'right';
    commandArea.appendChild(deleteAnswerButton);

    var submitButton = document.createElement('div');
    submitButton.classList.add('activeButton');
    submitButton.innerHTML = '确认发布';
    submitButton.style.padding = '10px 0px';
    //submitButton.style.backgroundColor = 'yellow';
    submitButton.style.marginTop = '20px';
    submitButton.style.marginBottom = '20px';
    ca.appendChild(submitButton);
    curAnswerNumber = 2;
    addAnswerButton.addEventListener('click',addAnswer)
    deleteAnswerButton.addEventListener('click',deleteAnswer);
    submitButton.addEventListener('click',doSubmit);
}
function initCount(){
    var ca = document.getElementById('countArea');
    ca.innerHTML = '';
    for(var i = 0; i < questionArray.length; i++){
        var q = questionArray[i];
        var clen = q.choices.length;
        var flag = false;
        var totalMemberNum = 0;
        for(var j = 0; j < clen; j++){
            totalMemberNum += q.choices[j].members.length;
            if(q.choices[j].members.find(memberId)>=0){
                flag = true;
            }
        }
        if(flag){
            var questionItem = document.createElement('div');
            ca.appendChild(questionItem);
            var questionTitle = document.createElement('p');
            questionTitle.innerHTML = '题目'+(i+1)+':'+q.title;
            questionItem.appendChild(questionTitle);
            var answerArea = document.createElement('div');
            questionItem.appendChild(answerArea);
            for(var j = 0; j < clen; j++){
                var choiceItem = document.createElement('div');
                //choiceItem.style.marginLeft = '10px';
                choiceItem.style.padding = '10px 10px';
                choiceItem.style.backgroundColor = '#ea4c89';
                choiceItem.style.color = '#fff';
                choiceItem.style.borderRadius = '5px';
                choiceItem.style.marginBottom = '5px';
                if(q.choices[j].members.find(memberId)>=0){
                    choiceItem.style.backgroundColor = 'rgb(138, 29, 20)';
                }
                var num = q.choices[j].members.length;
                var percent = 0;
                if(num<totalMemberNum){
                    percent = (100*num/totalMemberNum).toFixed(1);
                }
                else{
                    percent = 100;
                }
                choiceItem.innerHTML = q.choices[j].text+'('+percent+'%)';
                answerArea.appendChild(choiceItem);
            }
        }
    }
}
function initAdmin(){
    var ap = document.createElement('div');//ap = adminPage
    ap.style.minHeight = window.innerHeight;
    var title = document.createElement('div');
    title.style.fontSize = 22;
    title.style.padding = 20;
    title.style.fontWeight = 'bold';
    title.innerHTML = '尊敬的管理员,您可以:';
    ap.appendChild(title);
    var cmA = document.createElement('div');//cmA = commandArea
    ap.appendChild(cmA);
    var cQB = document.createElement('div');//cQB = createQuestionButton
    cQB.innerHTML = '发布题目<i class="fa fa-plus"></i>';
    cQB.classList.add('myButton');
    cmA.appendChild(cQB);
    cQB.addEventListener('click',function(){
        var ca = document.querySelector('#createArea');
        if(ca.style.display == 'block'){
            ca.style.display = 'none';
            this.querySelector('i').style.display = 'inline-block';
        }
        else{
            ca.style.display = 'block';
            this.querySelector('i').style.display = 'none';
        }
        var curCard = cc.getCurCard();
        curCard.scroll.refresh();
    });

    var cA = document.createElement('div');//cA = createArea;
    cA.id = 'createArea';
    cA.innerHTML = '<p>正在加载</p>';
    cmA.appendChild(cA);

    var lCB = document.createElement('div');//lCB = lookCountButton
    lCB.innerHTML = '查看统计<i class="fa fa-search"></i>';
    lCB.classList.add('myButton');
    cmA.appendChild(lCB);
    lCB.addEventListener('click',function(){
        var ca = document.querySelector('#countArea');
        if(ca.style.display == 'block'){
            ca.style.display = 'none';
            this.querySelector('i').style.display = 'inline-block';
        }
        else{
            ca.style.display = 'block';
            this.querySelector('i').style.display = 'none';
        }
        var curCard = cc.getCurCard();
        curCard.scroll.refresh();
    });


    var coA = document.createElement('div');//coA = countArea
    coA.id = 'countArea';
    coA.innerHTML = '<p>正在加载</p>';
    cmA.appendChild(coA);

    var footer = document.createElement('div');
    footer.innerHTML = '温馨提示:&nbsp&nbsp在本页面向上拉动即可回到答题页面,在答题页面向下拉动即可回到本页面';
    footer.style.padding = 20;
    footer.style.fontSize = 14;
    cmA.appendChild(footer);

    var curCard = null;
    if(noMoreQuestion){
        curCard = cc.newCard(ap,null,'没有更多的题目了','继续答题');
    }
    else{
        curCard = cc.newCard(ap,null,null,'继续答题');
        curCard.enablePullup();
    }
    curCard.disableDestory();
    curCard.setBgColor('#fff');
    initCreate();
    initCount();
}
function judgeAdmin(){
    answeredNumber = 0;
    var len = questionArray.length;
    for(var i = 0; i < len; i++){
        var q = questionArray[i];
        var clen = q.choices.length;
        var flag = false;
        for(var j = 0; j < clen; j++){
            if(q.choices[j].members.find(memberId)>=0){
                flag = true;
                break;
            }
        }
        if(flag){
            answeredNumber++;
        }
    };
    if(answeredNumber>=10){
        isAdmin = true;
    }
    if(answeredNumber>=len){
        isAdmin = true;
        noMoreQuestion = true;
    }
}
$(document).ready(function(){
    FastClick.attach(document.body);
    if(localStorage.memberId){
        memberId = localStorage.memberId;
    }
    else{
        localStorage.memberId = memberId = randomChar(30);
    }
    var jj = $('#jsonData').html();
    $('#jsonData').remove();
    questionArray = JSON.parse(jj);
    questionArray.sort(function(a,b){
        return a._time-b._time;
    });
    cc = new CardContainer('cardContainer',loadCard);
    nextQuestionIndex = -1;
    curQuestionSelected = -1;
    noMoreQuestion = false;
    isAdmin = false;
    judgeAdmin();
    if(isAdmin){
        initAdmin();
    }
    else{
        var desktop = document.createElement('div');
        var curCard = cc.newCard(desktop,null,null,'放手往前走吧!');
        curCard.enablePullup();
        showPoetry(desktop);
    }
});